package org.openfans.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openfans.domain.Facade;
import org.openfans.domain.Fans;
import org.openfans.domain.RootTag;
import org.openfans.domain.RootTagRemark;
import org.openfans.util.ThreadFans;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class RemarkRootTagFormController extends SimpleFormController {
	private Facade facade = null;

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	public RemarkRootTagFormController() {
		setCommandName("remark");
		setCommandClass(RootTagRemark.class);
	}

	@Override
	protected ModelAndView processFormSubmission(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		RootTagRemark remark = (RootTagRemark) command;
		remark.setRemarkDate(new Date());
		Fans fans = facade.getFans(ThreadFans.get().getFansId());

		remark.setFans(fans);
		facade.save(remark);
		remark.getTag().addRemark(remark);
		facade.save(remark.getTag());
		// return new ModelAndView("redirect:viewArticle.html?id="
		// + id);
		return null;
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		ThreadFans.authorize();

		int id = Integer.parseInt(request.getParameter("tag.tagId"));

		RootTag tag = (RootTag) facade.getTag(id);
		RootTagRemark remark = new RootTagRemark();
		remark.setTag(tag);
		return remark;
	}
}
